import axios from "axios"
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosRequestHeaders } from "axios"

interface Iceptors {
  requestSuccess: (config: AxiosRequestConfig<AxiosRequestHeaders>) => AxiosRequestConfig<AxiosRequestHeaders>
  requestFail: (err: any) => any
  responseSuccess: (config: AxiosResponse) => AxiosResponse
  responseFail: (err: any) => any
}
interface XTconfig extends AxiosRequestConfig {
  interceptors: Iceptors
}

class XTRequest {
  instance:AxiosInstance
  interceptors: Iceptors
  constructor(config: XTconfig) {
    this.instance = axios.create(config)
    this.interceptors = config.interceptors
    // 请求拦截
    this.instance.interceptors.request.use(
      this.interceptors.requestSuccess,
      this.interceptors.requestFail
      )

    this.instance.interceptors.response.use(
      this.interceptors.responseSuccess,
      this.interceptors.responseFail
    )
  }

  request(config:AxiosRequestConfig) {
    this.instance(config).then (res => {
      console.log(res)
    })
  }
}

export default new XTRequest({
  interceptors: {
    requestSuccess: config => {
      console.log("重写请求拦截- 成功")
      return config
    },
    requestFail: config => {
      console.log("重写请求拦截- 失败")
      return config
    },
    responseSuccess: config  => {
      console.log("重写响应拦截- 失败")
      return config
    },
    responseFail: config => {
      console.log("重写响应拦截- 失败")
      return config
    }


  }
})
